/*
** $Id: lfunc.c $
** 操作函数原型和闭包的辅助函数
** See Copyright Notice in lua.h
*/

#define lfunc_c
#define LUA_CORE

#include "lprefix.h"


#include <stddef.h>

#include "lua.h"

#include "ldebug.h"
#include "ldo.h"
#include "lfunc.h"
#include "lgc.h"
#include "lmem.h"
#include "lobject.h"
#include "lstate.h"


// 创建C闭包，nupvals表示upvalue的个数
CClosure *luaF_newCclosure (lua_State *L, int nupvals) {
  GCObject *o = luaC_newobj(L, LUA_VCCL, sizeCclosure(nupvals));
  CClosure *c = gco2ccl(o);
  c->nupvalues = cast_byte(nupvals);
  return c;
}

// 创建Lua闭包，nupvals表示upvalue的个数
LClosure *luaF_newLclosure (lua_State *L, int nupvals) {
  GCObject *o = luaC_newobj(L, LUA_VLCL, sizeLclosure(nupvals));
  LClosure *c = gco2lcl(o);
  c->p = NULL;
  c->nupvalues = cast_byte(nupvals);
  while (nupvals--) c->upvals[nupvals] = NULL;
  return c;
}


/*
** 通过新的关闭的upvalue填充闭包
*/
void luaF_initupvals (lua_State *L, LClosure *cl) {
  int i;
  for (i = 0; i < cl->nupvalues; i++) {
    GCObject *o = luaC_newobj(L, LUA_VUPVAL, sizeof(UpVal));
    UpVal *uv = gco2upv(o);
    uv->v.p = &uv->u.value;  /* 关闭 */
    setnilvalue(uv->v.p);
    cl->upvals[i] = uv;
    luaC_objbarrier(L, cl, uv);
  }
}


/*
** 在给定level上创建upvalue，并且将其链接到‘L'的打开upvalues列表的’prev'后
**/
static UpVal *newupval (lua_State *L, StkId level, UpVal **prev) {
  GCObject *o = luaC_newobj(L, LUA_VUPVAL, sizeof(UpVal));
  UpVal *uv = gco2upv(o);
  UpVal *next = *prev;
  uv->v.p = s2v(level);  /* 当前值存在于栈中 */
  uv->u.open.next = next;  /* 链接到打开的upvalue列表 */
  uv->u.open.previous = prev;
  if (next)
    next->u.open.previous = &uv->u.open.next;
  *prev = uv;
  if (!isintwups(L)) {  /* 线程不在’twups'列表中? */
    L->twups = G(L)->twups;  /* 将其链接进列表 */
    G(L)->twups = L;
  }
  return uv;
}


/*
** 查找并复用给定level上的upvalue，如果不存在则创建upvalue
*/
UpVal *luaF_findupval (lua_State *L, StkId level) {
  UpVal **pp = &L->openupval;
  UpVal *p;
  lua_assert(isintwups(L) || L->openupval == NULL);
  while ((p = *pp) != NULL && uplevel(p) >= level) {  /* 查找他 */
    lua_assert(!isdead(G(L), p));
    if (uplevel(p) == level)
      return p;
    pp = &p->u.open.next;
  }
  /* 没有找到，在‘pp'之后创建新的upvalue */
  return newupval(L, level, pp);
}


/*
** 使用错误消息‘err'调用对象’obj‘的 '__close' 方法，‘yy'表示调用是否yieldable(可让出)
** (这个方法占用 EXTRA_STACK.)
*/
static void callclosemethod (lua_State *L, TValue *obj, TValue *err, int yy) {
  StkId top = L->top.p;
  const TValue *tm = luaT_gettmbyobj(L, obj, TM_CLOSE);
  setobj2s(L, top, tm);  /* 调用元方法 */
  setobj2s(L, top + 1, obj);  /* 将’self'作为第一个参数 */
  setobj2s(L, top + 2, err);  /* ‘err'作为第二个参数 */
  L->top.p = top + 3;
  if (yy)
    luaD_call(L, top, 0);
  else
    luaD_callnoyield(L, top, 0);
}


/*
** 检测给定level上的对象是否有 __close 元方法，没有则引发错误
*/
static void checkclosemth (lua_State *L, StkId level) {
  const TValue *tm = luaT_gettmbyobj(L, s2v(level), TM_CLOSE);
  if (ttisnil(tm)) {  /* 没有元方法? */
    int idx = cast_int(level - L->ci->func.p);  /* 变量索引 */
    const char *vname = luaG_findlocal(L, L->ci, idx, NULL);
    if (vname == NULL) vname = "?";
    luaG_runerror(L, "variable '%s' got a non-closable value", vname);
  }
}


/*
** 准备并调用__close
** 如果status是CLOSEKTOP，对closing方法的调用将会入栈
** 否则，会被推送到upvalue的‘level'之后的值都会被关闭，因为之后所有的内容都不会再使用
*/
static void prepcallclosemth (lua_State *L, StkId level, int status, int yy) {
  TValue *uv = s2v(level);  /* 被关闭的值 */
  TValue *errobj;
  if (status == CLOSEKTOP)
    errobj = &G(L)->nilvalue;  /* 错误对象是nil*/
  else {  /* 'luaD_seterrorobj' 将设置top为 level + 2 */
    errobj = s2v(level + 1);  /* error object goes after 'uv' */
    luaD_seterrorobj(L, status, level + 1);  /* set error object */
  }
  callclosemethod(L, uv, errobj, yy);
}


/*
** ’tbclist‘增量的最大值，取决于增量类型 (这个宏假定'L'在他的使用范围内)
*/
#define MAXDELTA  \
	((256ul << ((sizeof(L->stack.p->tbclist.delta) - 1) * 8)) - 1)


/*
** 将一个变量插入到待关闭变量列表中
*/
void luaF_newtbcupval (lua_State *L, StkId level) {
  lua_assert(level > L->tbclist.p);
  if (l_isfalse(s2v(level)))
    return;  /* false不需要关闭 */
  checkclosemth(L, level);  /* 值必须有close方法 */
  while (cast_uint(level - L->tbclist.p) > MAXDELTA) {
    L->tbclist.p += MAXDELTA;  /* 在最大增量上创建一个虚拟节点 */
    L->tbclist.p->tbclist.delta = 0;
  }
  level->tbclist.delta = cast(unsigned short, level - L->tbclist.p);
  L->tbclist.p = level;
}


void luaF_unlinkupval (UpVal *uv) {
  lua_assert(upisopen(uv));
  *uv->u.open.previous = uv->u.open.next;
  if (uv->u.open.next)
    uv->u.open.next->u.open.previous = uv->u.open.previous;
}


/*
** 关闭所有给定栈level上的upvalue
*/
void luaF_closeupval (lua_State *L, StkId level) {
  UpVal *uv;
  StkId upl;  /* 'uv' 指向的栈索引 */
  while ((uv = L->openupval) != NULL && (upl = uplevel(uv)) >= level) {
    TValue *slot = &uv->u.value;  /* 值的新位置 */
    lua_assert(uplevel(uv) < L->top.p);
    luaF_unlinkupval(uv);  /* 从'openupval'列表中移除upvalue */
    setobj(L, slot, uv->v.p);  /* 移动值到upvalue的插槽 */
    uv->v.p = slot;
    if (!iswhite(uv)) {  /* 不是白色也不是死的? */
      nw2black(uv);  /* 关闭的upvalue不能是灰色的 */
      luaC_barrier(L, uv, slot);
    }
  }
}


/*
** 从tbclist和它的虚拟节点移除第一个元素
*/
static void poptbclist (lua_State *L) {
  StkId tbc = L->tbclist.p;
  lua_assert(tbc->tbclist.delta > 0);  /* 第一个元素不能是虚拟的 */
  tbc -= tbc->tbclist.delta;
  while (tbc > L->stack.p && tbc->tbclist.delta == 0)
    tbc -= MAXDELTA;  /* 移除虚拟节点 */
  L->tbclist.p = tbc;
}


/*
** 关闭所有的upvalues和tbclist变量直到level，返回恢复的level
*/
StkId luaF_close (lua_State *L, StkId level, int status, int yy) {
  ptrdiff_t levelrel = savestack(L, level);
  luaF_closeupval(L, level);  /* 首先，关闭upvalue */
  while (L->tbclist.p >= level) {  /* 遍历这个level下的tbc */
    StkId tbc = L->tbclist.p;  /* 获取变量索引 */
    poptbclist(L);  /* 从列表中移除 */
    prepcallclosemth(L, tbc, status, yy);  /* 关闭变量 */
    level = restorestack(L, levelrel);
  }
  return level;
}


// 创建函数原型
Proto *luaF_newproto (lua_State *L) {
  GCObject *o = luaC_newobj(L, LUA_VPROTO, sizeof(Proto));
  Proto *f = gco2p(o);
  f->k = NULL;
  f->sizek = 0;
  f->p = NULL;
  f->sizep = 0;
  f->code = NULL;
  f->sizecode = 0;
  f->lineinfo = NULL;
  f->sizelineinfo = 0;
  f->abslineinfo = NULL;
  f->sizeabslineinfo = 0;
  f->upvalues = NULL;
  f->sizeupvalues = 0;
  f->numparams = 0;
  f->is_vararg = 0;
  f->maxstacksize = 0;
  f->locvars = NULL;
  f->sizelocvars = 0;
  f->linedefined = 0;
  f->lastlinedefined = 0;
  f->source = NULL;
  return f;
}

// 释放函数原型
void luaF_freeproto (lua_State *L, Proto *f) {
  luaM_freearray(L, f->code, f->sizecode);
  luaM_freearray(L, f->p, f->sizep);
  luaM_freearray(L, f->k, f->sizek);
  luaM_freearray(L, f->lineinfo, f->sizelineinfo);
  luaM_freearray(L, f->abslineinfo, f->sizeabslineinfo);
  luaM_freearray(L, f->locvars, f->sizelocvars);
  luaM_freearray(L, f->upvalues, f->sizeupvalues);
  luaM_free(L, f);
}


/*
** 获取方法‘func'的’line'行中查找第n个局部变量
** 如果没有找到则返回NULL
*/
const char *luaF_getlocalname (const Proto *f, int local_number, int pc) {
  int i;
  for (i = 0; i<f->sizelocvars && f->locvars[i].startpc <= pc; i++) {
    if (pc < f->locvars[i].endpc) {  /* 变量活跃? */
      local_number--;
      if (local_number == 0)
        return getstr(f->locvars[i].varname);
    }
  }
  return NULL;  /* not found */
}

